package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.constants.NewsAutoScanConstants;
import com.heima.model.common.constants.WmMediaConstans;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {



    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    WmUserMapper wmUserMapper;


    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser wmUser = null;
        if(wmNews.getUserId()!=null){
             wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser!=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();
        Integer curPage = dto.getPage();
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){

            dto.setTitle("%"+dto.getTitle()+"%");
        }

        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        long listCount = wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult = new PageResponseResult(curPage, dto.getSize(), listCount, listAndPage);
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或者8的文章并且发布时间小于当前时间
        //并拿到id
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId)
        );
        List<Integer> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());

        return idList;
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //检查参数
        if(dto==null|| dto.getId()==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.ARTICEL_NOT_PUBLISHED);
        }

        //修改文章状态,同步到app端  todo


        if(dto.getEnable()!=null&&dto.getEnable()>-1&&dto.getEnable()<2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }

        if(wmNews.getArticleId()!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("enable",dto.getEnable());
            map.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public WmNews findById(Integer id) {
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        return wmNews;
    }

    /**
     * 修改文章
     *
     * @param wmNews
     * @return
     */
    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        updateById(wmNews);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //检查参数
        if (id == null) {
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取数据
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断当前文章的状态  status=9,enable=1

        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable().equals(WmMediaConstans.WM_NEWS_UPENABLE)){
            return ResponseResult.errorResult(AppHttpCodeEnum.ARTICEL_ALREADY_PUBLISHED);
        }
        //去除素材与文章的关系

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数检查
        if(id==null){
         throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //执行检查
        WmNews wmNews = getById(id);
        if(wmNews==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //返回结果
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.web-site}")
    private String webSite;
    /**
     * 查询所有自媒体文章
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {

        //参数校验
        if(wmNewsPageReqDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        wmNewsPageReqDto.checkParam();

        //执行查询

        IPage<WmNews> pageParam = new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        if(wmNewsPageReqDto.getStatus()!=null){
            query.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
        }
        if(wmNewsPageReqDto.getKeyword()!=null){
            query.eq(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }
        if(wmNewsPageReqDto.getChannelId()!=null){
            query.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }
        if(wmNewsPageReqDto.getBeginPubDate()!=null&&wmNewsPageReqDto.getEndPubDate()!=null){
            query.between(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate());
        }

        //获取登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer id = user.getId();
        query.eq(WmNews::getUserId,id);

        query.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> pageResult = page(pageParam, query);
        //返回结果

        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsPageReqDto.getPage()
        ,wmNewsPageReqDto.getSize(),pageResult.getTotal(),pageResult.getRecords()
        );

        //处理图片封面,结合前端做
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }


    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 自媒体文章发布
     *
     * @param wmNewsDto
     * @param isSubmit  是否为提交 1 为提交,图片保存 0为草稿,图片不存
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto wmNewsDto, Short isSubmit) {
        //参数校验
        if(wmNewsDto==null||wmNewsDto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //保存或者修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);

        if (wmNewsDto.getType().equals(WmMediaConstans.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        //处理文章封面
        String images = imageListToStr(wmNewsDto.getImages(),webSite);
        if(StringUtils.isNotBlank(images)){
            wmNews.setImages(images);
        }
        saveWmNews(wmNews);
        //关联文章和素材的关系(isSubmit  1,提交.关联  0,不关联)
        //解析文章内容中的图片列表
        List<Map> Content = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        List<String> materialsList = parseContentImages(Content);
        //关联文章内容和素材的关系
        if(isSubmit.equals(WmMediaConstans.WM_NEWS_SUMMIT_STATUS)&&materialsList.size()>0){
            saveRelativeInfoForContent(materialsList,wmNews.getId());
        }
        //关联文章封面和素材的关系

        if(isSubmit.equals(WmMediaConstans.WM_NEWS_SUMMIT_STATUS)){
            saveRelativeInfoForCover(wmNewsDto,materialsList,wmNews);
        }
        //TODO 发消息给admin审核
        Map map = new HashMap();
        map.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));

        //返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    //保存文章  封面和素材关系
    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, List<String> materialsList, WmNews wmNews) {
        //获取dto图片封面
        List<String> images = wmNewsDto.getImages();
        //判断type是否为自动

        if(wmNewsDto.getType().equals(WmMediaConstans.WM_NEWS_TYPE_AUTO)){
            int size = materialsList.size();

            if(size>0&&size<=2){
                materialsList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WmMediaConstans.WM_NEWS_SINGLE_IMAGE);
            }else if(size>2){
                materialsList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WmMediaConstans.WM_NEWS_MANY_IMAGE);
            }else{
                wmNews.setType(WmMediaConstans.WM_NEWS_NONE_IMAGE);
            }
            if(images!=null){
                wmNews.setImages(imageListToStr(images,webSite));
            }
            updateById(wmNews);
        }
        //执行保存文章封面和素材关系
        if(images!=null&&images.size()>0){
            saveRelativeInfoForImage(images,wmNews.getId());
        }


    }
    //保存文章封面和素材的关系
    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        images = images.stream().map(y ->
                y.replace(webSite,"")
                        .replace(" ","")
        ).collect(Collectors.toList());
        saveRelativeInfo(images,wmNewsId,WmMediaConstans.WM_IMAGE_REFERENCE);
    }

    //保存文章  内容和素材的关系
    private void saveRelativeInfoForContent(List<String> materialsList, Integer wmNewsId) {
        saveRelativeInfo(materialsList,wmNewsId,WmMediaConstans.WM_CONTENT_REFERENCE);
    }


    @Autowired
    WmMaterialMapper wmMaterialMapper;
    private void saveRelativeInfo(List<String> materialsList, Integer wmNewsId, Short type) {
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialsList).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        //判断文章是否存在

        if(dbMaterials==null||dbMaterials.size()==0){
            throw new CustomException(AppHttpCodeEnum.MATERIAL_IS_NULL);
        }
        Map<String, Integer> materialMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        List<Integer> materialIds = new ArrayList<>();
        for (String url : materialsList) {
            Integer id = materialMap.get(url);
            if(id==null){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_IS_NULL);
            }
            materialIds.add(id);

        }
        //批量保存 用xml文件
        wmNewsMaterialMapper.saveRelations(materialIds,wmNewsId,type);
    }

    private List<String> parseContentImages(List<Map> content) {
        List<String> materialsList = new ArrayList<>();
        for (Map<String, String> map : content) {
            if(map.get("type").equals(WmMediaConstans.WM_NEWS_TYPE_IMAGE)){
                String imagesUrl = map.get("value").replace(webSite,"").replace(" ","");
                materialsList.add(imagesUrl);
            }
        }

        return materialsList;
    }

    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WmMediaConstans.WM_NEWS_UPENABLE);//上架成功

        if(wmNews.getId()==null){
            //创建
            save(wmNews);
        }else{
            //修改
            //先删后加
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imageListToStr(List<String> images, String webSite) {
        if(images.size()>0){
            return images.toString()
                    .replace("[","")
                    .replace("]","")
                    .replace(webSite,"")
                    .replace(" ","");
        }
        return null;
    }
}
